//
//  XMPersonInfoController.m
//  XiaoMiao
//
//  Created by 23 on 2018/1/28.
//  Copyright © 2018年 smallyou. All rights reserved.
//

#import "XMPersonInfoController.h"
#import "BRStringPickerView.h"
#import "AddressProvinceCityController.h"

#import "TZImageManager.h"
#import "TZImagePickerController.h"

#define NUMBERS @"0123456789"
typedef NS_ENUM(NSUInteger, XMPersonInfoVCType) {
    XMPersonInfoVCTypeMine,
    XMPersonInfoVCTypeOther,
};

@interface XMPersonInfoController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate, UIActionSheetDelegate,UITextViewDelegate,UITextFieldDelegate,UIAlertViewDelegate>
/** <#属性#> */
@property (nonatomic, assign) XMPersonInfoVCType VCType;
/** <#属性#> */
@property (nonatomic, copy) NSString *partyId;
/** <#属性#> */
@property (nonatomic, strong) LoginInfoModel *infoModel;

@property (weak, nonatomic) IBOutlet UIControl *headImageControl;
@property (weak, nonatomic) IBOutlet UIControl *nameControl;
@property (weak, nonatomic) IBOutlet UIControl *sexControl;
@property (weak, nonatomic) IBOutlet UIControl *ageControl;
@property (weak, nonatomic) IBOutlet UIControl *locationControl;

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
@property (weak, nonatomic) IBOutlet UITextField *ageTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;
@property (weak, nonatomic) IBOutlet UITextView *addressTextView;
@property (weak, nonatomic) IBOutlet UILabel *addressPlaceHolderLabel;
@property (weak, nonatomic) IBOutlet UILabel *identityLabel;

//
@property (nonatomic,strong) XMNewPersonDetailModel *listModel;
@property (nonatomic,strong) UIImagePickerController *imagePicker;

@end

@implementation XMPersonInfoController

- (instancetype)initWithMine {
    return [self initWithVCType:XMPersonInfoVCTypeMine partyId:nil];
}

- (instancetype)initWithOther:(NSString *)partyId {
    return [self initWithVCType:XMPersonInfoVCTypeOther partyId:partyId];
}

- (instancetype)initWithVCType:(XMPersonInfoVCType)VCType partyId:(NSString *)partyId {
    if (self = [super init]) {
        self.VCType = VCType;
        self.partyId = partyId;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    
    [self getUserDetail];
    
    [self isCanUsePhotos];

}

#pragma mark - UI

- (void)setupUI
{
    self.title = @"编辑个人资料";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(V2uploadUserDetail)];
    self.headImageView.layer.cornerRadius = 4.f;
    self.headImageView.layer.masksToBounds = YES;
    
    NSArray <UIControl *>*controls = @[self.headImageControl, self.sexControl, self.locationControl];
    for (UIControl *control in controls) {
        [control addTarget:self action:@selector(controlTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self.nameTextField addTarget:self action:@selector(textFieldChange) forControlEvents:UIControlEventEditingChanged];
    
        [self.phoneTextField addTarget:self action:@selector(TextFieldChange) forControlEvents:UIControlEventEditingChanged];
}


- (void)updateUI
{
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.listModel.profile] placeholderImage:kDefaultPlaceholdeImage];
    self.nameTextField.text = self.listModel.realName;
    self.sexLabel.text = self.listModel.sex;
    self.ageTextField.text = self.listModel.age;
    self.ageTextField.delegate = self;
    self.phoneTextField.text = self.listModel.phone;
    NSString *province = self.listModel.province.length ? self.listModel.province : @"";
    NSString *city = self.listModel.city.length ? self.listModel.city : @"";
    self.locationLabel.text = [NSString stringWithFormat:@"%@ %@", province, city];
    self.addressTextView.delegate = self;
    self.addressTextView.text = self.listModel.addr;
    self.addressPlaceHolderLabel.hidden = self.listModel.addr.length;
    NSString *identityText;
    if ([self.listModel.type isEqualToString:@"1"]) {
        identityText = @"医生";
    }else if ([self.listModel.type isEqualToString:@"2"]){
        identityText = @"咨询师";
    }else{
        identityText = @"会员";

    }
    self.identityLabel.text = identityText;

}

#pragma mark - action
- (void)actionSave
{

    //保存个人信息
    if ([NSString app_isBlankString:self.listModel.realName]) {
        [KLProgressHUD showPromptHUDWithMessage:@"请输入姓名"];
        return;
    }
    
    [self requestUpdatePersonInfo];
}

- (void)controlTouchUpInside:(UIControl *)sender
{
    if (sender == self.headImageControl) { //头像
        [self p_showAddHeadImage];
    }else if (sender == self.sexControl) { //性别
        [self p_showSexPicker];
    }else if (sender == self.locationControl) { //地址
        [self p_showLocationList];
    }
}

- (void)textFieldChange:(UITextField *)textfield{
    if (textfield == self.nameTextField) {
            self.listModel.realName = self.nameTextField.text;
    }
//    else if (textfield == self.phoneTextField){
//                    self.listModel.phone = self.phoneTextField.text;
//    }

}


#pragma mark - Private
- (void)p_showAddHeadImage {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择相片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    
    [actionSheet showInView:self.view];
}

- (void)p_showSexPicker {
    WEAKSELF
    [BRStringPickerView showStringPickerWithTitle:nil dataSource:kSexArray defaultSelValue:self.listModel.sex resultBlock:^(id selectValue) {
        if ([NSString app_isBlankString:weakSelf.listModel.sex] && [NSString app_isBlankString:selectValue]) {
            weakSelf.listModel.sex = kSexArray[0];
        }else {
            weakSelf.listModel.sex = selectValue;
        }
        
        [weakSelf updateUI];
    }];
}

- (void)p_showLocationList {
    AddressProvinceCityController *address = [[AddressProvinceCityController alloc] initWithAddressVCType:AddressVCTypeProvince parentId:@"" titleName:@""];
    [self.navigationController pushViewController:address animated:YES];

    WEAKSELF
    [address setAddressCompleted:^(NSString *province, NSString *city) {

        weakSelf.listModel.province = province;
        weakSelf.listModel.city = city;
        [weakSelf updateUI];
    }];
}

#pragma mark ----uitextViewDelegate
-(void)textViewDidChange:(UITextView *)textView{
    self.listModel.addr = self.addressTextView.text;
    self.addressPlaceHolderLabel.hidden = textView.text.length;
    
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) { // 打开相机
        if (![AppGlobal isCameraDeviceAvalable]) {
            UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
        }
        if (!self.imagePicker) {
            self.imagePicker = [[UIImagePickerController alloc]init];
        }

        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.allowsEditing = NO;
        
        self.imagePicker.showsCameraControls = YES;
        self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
        self.imagePicker.mediaTypes = @[(NSString*)kUTTypeImage];
        [self presentViewController:self.imagePicker animated:YES completion:nil];
        
    } else if (1 == buttonIndex) { // 打开照片库
        if (![AppGlobal isAssetsLibraryAvalable]) {
            return;
        }
        [self selectPhotoToUpload];

    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSCharacterSet *cs;
    if(textField == self.ageTextField)
    {
        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)
        {
            [KLProgressHUD showErrorHUDWithMessage:@"只能输入数字"];
            //输入了非法字符
            return NO;
        }
    }
    
    //其他的类型不需要检测，直接写入
    return YES;
}

#pragma mark ----TZImagePicker----
//从相册中选取
-(void)selectPhotoToUpload{
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil ];
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowCrop = YES;
    
    //裁剪图片VC设置
    NSInteger width = kScreenWidth;
    NSInteger height = kScreenWidth;
    NSInteger top = (kScreenHeight-height)/2;
    imagePickerVC.cropRect = CGRectMake(0, top, width, height);
    

    MJWeakSelf
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count>0) {
            weakSelf.headImageView.image = photos[0];
            [weakSelf requestUploadImage];
        }
    }];
    [self presentViewController:imagePickerVC animated:YES completion:nil];
    
}

#pragma mark - KGetImageDelegate


//获取图片信息
- (void)reloadPhotoArrayImage:(UIImage *)image {
    MJWeakSelf
    //获取相册最新的图片信息 也就是刚刚拍照保存的
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    PHAsset *phasset = [assetsFetchResults lastObject];
    
    [MBProgressHUD hideHUDWithAnimated:YES];
    //裁剪图片VC
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc]initCropTypeWithAsset:phasset photo:image completion:^(UIImage *cropImage, id asset) {
        weakSelf.headImageView.image = cropImage;
        [weakSelf requestUploadImage];
        
    }];
    //裁剪图片VC设置
    NSInteger width = kScreenWidth;
    NSInteger height = kScreenWidth;
    NSInteger top = (kScreenHeight-height)/2;
    imagePickerVC.cropRect = CGRectMake(0, top, width, height);
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowCrop = YES;
    
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count>0) {
            weakSelf.headImageView.image = photos[0];
            [weakSelf requestUploadImage];

        }
    }];
    [self presentViewController:imagePickerVC animated:YES completion:nil];
    
}


#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *  image = info[UIImagePickerControllerOriginalImage];

    [picker dismissViewControllerAnimated:YES completion:^{
        if (![self isCanUsePhotos]) {
            [KLProgressHUD showErrorHUDWithMessage:@"需要保存到相册权限"];
            return;
        }
        
        if (image) {
            //保存图片
            [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error){
                if (!error) {
                    [self reloadPhotoArrayImage:image];
                }
            }];
        }
    }];
}

#pragma mark - Request
- (void)loadPersonInfo
{
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:kLoadingMsg];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    switch (self.VCType) {
        case XMPersonInfoVCTypeMine: param[@"partyId"] = [LoginInfoModel getLoginInfo].id; break;
        case XMPersonInfoVCTypeOther: param[@"partyId"] = self.partyId; break;
    }
    
    [AppNetwork getWithUrl:kPersonInfoPath refreshCache:NO params:param success:^(id response) {
        progressHUD.hidden = YES;
        
        self.infoModel = [LoginInfoModel mj_objectWithKeyValues:response[@"partyView"]];
        
        [self updateUI];
        
    } fail:^(AppError *error) {
        progressHUD.hidden = YES;
        [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
    }];
}

- (void)requestUpdatePersonInfo
{
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"修改中.."];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    switch (self.VCType) {
        case XMPersonInfoVCTypeMine: param[@"partyId"] = [LoginInfoModel getLoginInfo].id; break;
        case XMPersonInfoVCTypeOther: param[@"partyId"] = self.partyId; break;
    }
    
    if (self.listModel.age.length != 0) {
        
        if (self.listModel.age.length !=4 ||(![[self.listModel.age substringWithRange:NSMakeRange(0,2)] isEqualToString:@"19"]&&![[self.listModel.age substringWithRange:NSMakeRange(0,2)] isEqualToString:@"20"])) {
            [KLProgressHUD showErrorHUDWithMessage:@"请输入正确年份 如1970"];
            return;
        }
    }
    
    param[@"age"]   = self.infoModel.age;
    param[@"city"]      = self.infoModel.city;
    param[@"profile"]   = self.infoModel.profile;
    param[@"province"]  = self.infoModel.province;
    param[@"realName"]  = self.infoModel.realName;
    param[@"sex"]       = self.infoModel.sex;

    WEAKSELF
    [AppNetwork postWithUrl:kUpdatePersonInfoPath refreshCache:NO params:param success:^(id response) {
        progressHUD.hidden = YES;
        
        switch (self.VCType) {
            case XMPersonInfoVCTypeMine: {
                [LoginInfoModel persistLoginInfo:self.infoModel];
                [AppNotificationHelpper postNotificationName:@"infoChangeNoti" object:nil];
            }
                break;
                
            case XMPersonInfoVCTypeOther: {
                [AppNotificationHelpper postNotificationName:@"_updateConsumerListNotification_" object:nil];
            }
                break;
        }
        
        [KLProgressHUD showSuccessHUDWithSuperView:nil message:@"保存成功" isHudEnable:YES completed:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        
    } fail:^(AppError *error) {
        progressHUD.hidden = YES;
        [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
    }];
}

// 上传照片
- (void)requestUploadImage {
    WEAKSELF
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"上传中.."];
    [AppHttpClient userModule_uploadImage:self.headImageView.image completion:^(BOOL success, NSString *imageUrl, NSString *errorMsg) {
        progressHUD.hidden = YES;
        if (success) {
            weakSelf.listModel.profile = imageUrl;
            
        }else {
            [KLProgressHUD showErrorHUDWithMessage:errorMsg];
        }
    }];
}



#pragma mark  ----v2NetWork
//修改用户
-(void)V2uploadUserDetail{
    [self.view endEditing:YES];
    XMUserCreateModel * model = [[XMUserCreateModel alloc]init];
    model.profile = self.listModel.profile;
    model.realName = self.listModel.realName;
    if (self.ageTextField.text.length != 0) {
        
        if (self.ageTextField.text.length !=4 ||(![[self.ageTextField.text substringWithRange:NSMakeRange(0,2)] isEqualToString:@"19"]&&![[self.ageTextField.text substringWithRange:NSMakeRange(0,2)] isEqualToString:@"20"])) {
            [KLProgressHUD showErrorHUDWithMessage:@"请输入正确年份 如1970"];
            return;
        }
        
        self.listModel.age =self.ageTextField.text;
        model.age = self.listModel.age;
    }


    model.sex = self.listModel.sex;
    model.province = self.listModel.province;
    model.city = self.listModel.city;
    model.addr = self.listModel.addr;

    model.partyId = [LoginInfoModel getLoginInfo].id;

    

    [KLProgressHUD showWaitingHUD];
    MJWeakSelf
    [AppNetwork album_V2uploadPersonDetailInfoWithCreateModel:model Completion:^(BOOL success, XMNewPersonDetailModel *model, AppError *error) {


        [KLProgressHUD hideHUDWithAnimated:YES];
        if (success) {
            switch (self.VCType) {
                case XMPersonInfoVCTypeMine: {
                    LoginInfoModel * infoModel = [[LoginInfoModel alloc]init];
                    infoModel.city = weakSelf.listModel.city;
                    infoModel.province = weakSelf.listModel.province;
                    infoModel.realName = weakSelf.listModel.realName;
                    infoModel.sex = weakSelf.listModel.sex;
                    infoModel.profile = weakSelf.listModel.profile;
                    infoModel.age = weakSelf.listModel.age;
                    infoModel.addr = weakSelf.listModel.addr;
                    infoModel.id = [LoginInfoModel getLoginInfo].id;
                    
                    [LoginInfoModel persistLoginInfo:infoModel];
                    [AppNotificationHelpper postNotificationName:@"infoChangeNoti" object:nil];
                }
                    break;
                    
                case XMPersonInfoVCTypeOther: {
                    [AppNotificationHelpper postNotificationName:@"_updateConsumerListNotification_" object:nil];
                }
                    break;
            }
            
            [KLProgressHUD showSuccessHUDWithSuperView:nil message:@"保存成功" isHudEnable:YES completed:^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
        }
    }];
}


-(void)getUserDetail{
    [KLProgressHUD showWaitingHUD];
    MJWeakSelf
    [AppNetwork album_V2GetPersonDetailInfoWithPartyId:[LoginInfoModel getLoginInfo].id Completion:^(BOOL success, XMNewPersonDetailModel *model, AppError *error) {
        
        [KLProgressHUD hideHUDWithAnimated:YES];
        if (success) {
            
            weakSelf.listModel = model;
            [weakSelf updateUI];

        }else{
            [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
        }
    }];
    
}
#pragma mark ---alterViewDelegate
-(void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

//判断是否有相册权限
- (BOOL)isCanUsePhotos {
    PHAuthorizationStatus photoAuthorStatus = [PHPhotoLibrary authorizationStatus];
    if (photoAuthorStatus == kCLAuthorizationStatusRestricted || photoAuthorStatus ==kCLAuthorizationStatusDenied){
        return NO;
    }else if (photoAuthorStatus == kCLAuthorizationStatusNotDetermined){
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            
        }];
    }
    return YES;
}



@end
